<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { showFailToast, showLoadingToast, closeToast } from 'vant'

interface MedicalGuide {
  medicalGuideId: number
  theme: string
  medicalGuideName: string
  dayDateTime: string
  viewer: number
  details: string
}

interface ApiResponse {
  mes: string
  code: number
  data: MedicalGuide[]
}

const router = useRouter()

// 数据相关
const guideList = ref<MedicalGuide[]>([])
const loading = ref(false)
const finished = ref(false)

// 通知横幅数据（第一条数据的theme）
const noticeTheme = ref<{ title: string; subtitle: string } | null>(null)

// 获取就医指南数据
const fetchMedicalGuides = async () => {
  try {
    loading.value = true
    showLoadingToast({
      message: '加载中...',
      forbidClick: true
    })

    const response = await fetch('http://localhost:5029/api/Health/MedicalShow', {
      method: 'GET',
      headers: {
        'Content-Type': 'application/json',
        'accept': 'text/plain'
      }
    })

    if (!response.ok) {
      throw new Error('网络请求失败')
    }

    const result: ApiResponse = await response.json()

    if (result.code === 300 && result.data && result.data.length > 0) {
      guideList.value = result.data
      
      // 处理第一条数据的theme作为通知横幅
      if (result.data.length > 0 && result.data[0] && result.data[0].theme) {
        const firstGuide = result.data[0]
        const themeText = firstGuide.theme
        // 解析theme字段，分离"叮~你有一份"、"门诊挂号预约指南 待查收"、"请点击查收~"
        const lines = themeText.split('\r\n').filter(line => line.trim())
        
        if (lines.length >= 2) {
          const firstLine = lines[0]?.trim() || ''
          const secondLine = lines[lines.length - 1]?.trim() || ''
          
          // 分离标题和"待查收"
          const firstParts = firstLine.split('待查收')
          const title = firstParts[0]?.replace('叮~你有一份', '').trim() || ''
          
          noticeTheme.value = {
            title: title,
            subtitle: secondLine
          }
        } else if (lines.length === 1) {
          // 如果只有一行，尝试解析
          const line = lines[0]?.trim() || ''
          const parts = line.split('待查收')
          if (parts.length > 1) {
            const title = parts[0]?.replace('叮~你有一份', '').trim() || ''
            noticeTheme.value = {
              title: title,
              subtitle: '请点击查收~'
            }
          } else {
            noticeTheme.value = {
              title: line.replace('叮~你有一份', '').replace('待查收', '').trim(),
              subtitle: '请点击查收~'
            }
          }
        }
      }
    } else {
      guideList.value = []
      if (result.code !== 300) {
        showFailToast(result.mes || '获取数据失败')
      }
    }
    
    finished.value = true
  } catch (error) {
    console.error('获取就医指南失败:', error)
    guideList.value = []
    showFailToast('网络请求失败，请检查网络连接')
  } finally {
    loading.value = false
    closeToast()
  }
}

// 格式化日期
const formatDate = (dateString: string) => {
  try {
    const date = new Date(dateString)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    return `${year}-${month}-${day}`
  } catch (error) {
    return dateString.split('T')[0] // 如果解析失败，返回原始日期的日期部分
  }
}

// 点击指南项
const handleGuideClick = (guide: MedicalGuide) => {
  // 跳转到指南详情页
  router.push({
    name: 'guide-detail',
    params: { id: guide.medicalGuideId.toString() }
  })
}

// 点击通知横幅
const handleNoticeClick = () => {
  // 点击通知横幅时，可以跳转到第一条指南的详情
  if (guideList.value.length > 0 && guideList.value[0]) {
    handleGuideClick(guideList.value[0])
  }
}

// 初始化
onMounted(() => {
  fetchMedicalGuides()
})
</script>

<template>
  <div class="medical-guide-view">
    <!-- 导航栏 -->
    <van-nav-bar
      title="就医指南"
      left-text=""
      left-arrow
      @click-left="router.back()"
      class="nav-bar"
    >
      <template #right>
        <van-icon name="ellipsis" size="18" />
        <van-icon name="aim" size="18" style="margin-left: 12px" />
      </template>
    </van-nav-bar>

    <!-- 通知横幅 -->
    <div v-if="noticeTheme" class="notice-banner" @click="handleNoticeClick">
      <div class="notice-content">
        <div class="notice-line">
          <div class="notice-left">
            <span class="notice-text">叮~你有一份</span>
            <span class="notice-title">{{ noticeTheme.title }}</span>
          </div>
          <span class="notice-status">待查收</span>
        </div>
        <div class="notice-subtitle">{{ noticeTheme.subtitle }}</div>
      </div>
    </div>

    <!-- 全部指南标题 -->
    <div class="section-title">
      <h2>全部指南</h2>
    </div>

    <!-- 指南列表 -->
    <div class="list-section">
      <div v-if="loading && guideList.length === 0" class="loading-state">
        加载中...
      </div>
      
      <div v-else-if="guideList.length === 0" class="empty-state">
        暂无数据
      </div>

      <div v-else class="guide-list">
        <div
          v-for="guide in guideList"
          :key="guide.medicalGuideId"
          class="guide-item"
          @click="handleGuideClick(guide)"
        >
          <div class="guide-content">
            <div class="guide-header">
              <h3 class="guide-title">{{ guide.medicalGuideName }}</h3>
              <van-icon name="arrow" size="16" class="guide-arrow" />
            </div>
            <div class="guide-footer">
              <span class="guide-date">{{ formatDate(guide.dayDateTime) }}</span>
              <span class="guide-viewer">{{ guide.viewer }}人已查看</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
.medical-guide-view {
  width: 100%;
  min-height: 100vh;
  background-color: #f7f8fa;
}

.nav-bar {
  background-color: #fff;
}

/* 通知横幅 */
.notice-banner {
  background: linear-gradient(135deg, #e6f7ff 0%, #bae7ff 100%);
  margin: 12px 16px;
  border-radius: 8px;
  padding: 16px;
  cursor: pointer;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.notice-content {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.notice-line {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 8px;
}

.notice-left {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
  gap: 4px;
  flex: 1;
}

.notice-text {
  font-size: 14px;
  color: #323233;
}

.notice-title {
  font-size: 14px;
  font-weight: bold;
  color: #1989fa;
}

.notice-status {
  font-size: 14px;
  color: #969799;
  white-space: nowrap;
}

.notice-subtitle {
  font-size: 14px;
  color: #1989fa;
  font-weight: 500;
}

/* 全部指南标题 */
.section-title {
  padding: 16px 16px 8px;
  background-color: #fff;
  border-bottom: 1px solid #ebedf0;
}

.section-title h2 {
  font-size: 16px;
  font-weight: bold;
  color: #323233;
  margin: 0;
}

/* 列表区域 */
.list-section {
  padding: 8px 16px;
  background-color: #fff;
}

.loading-state,
.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #969799;
  font-size: 14px;
}

.guide-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.guide-item {
  background-color: #f7f8fa;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 8px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.guide-item:active {
  background-color: #ebedf0;
}

.guide-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.guide-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.guide-title {
  flex: 1;
  font-size: 16px;
  font-weight: bold;
  color: #323233;
  margin: 0;
  margin-right: 12px;
  line-height: 1.4;
}

.guide-arrow {
  color: #c8c9cc;
  flex-shrink: 0;
  margin-top: 2px;
}

.guide-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.guide-date {
  font-size: 12px;
  color: #969799;
}

.guide-viewer {
  font-size: 12px;
  color: #969799;
  display: flex;
  align-items: center;
  gap: 4px;
}
</style>
